/**
 * 用户信息添加编辑窗体
 */
role.win = role.win || Ext.extend(Ext.Window,{
	initComponent:function(){
		Ext.apply(this, {
			resizable : false,																					
			animateTarget : document.body,																		
			closeAction: 'hide',																				
			plain: true,
			modal: true,
			width: 400,
			items:this.getForm()
		}),
		role.win.superclass.initComponent.call(this);
	},
	getForm : function(){
		return {
        	xtype:'form',
            bodyStyle:'padding:10px',
            labelWidth : 80,
            defaults : {
            	width : 260	
            },
            defaultType:'textfield',
            border:false,
            items:[{
                fieldLabel:'角色名',
                blankText : '角色名不能为空,请输入!',
                allowBlank:false,
                maxLength : 20,
                maxLengthText : '角色名的最大长度为20个字符',	
                name:'roleName'
            },{
                xtype:'hidden', 
                name:'id',
                value:'0',
        	    anchor:'90%'
            },new Ext.ux.ComboBoxTree({																		
				fieldLabel : '上级角色',																			
				hiddenName : 'parentName',																		
				tree : new Ext.tree.TreePanel({																
					rootVisible:false,																			
					loader: new Ext.tree.TreeLoader({														
						dataUrl:'role/getRoleTree.jhtml' ,														
						clearOnLoad: true,																	
						listeners: {																		
							'beforeload': function(treeloader, node) {										
								treeloader.baseParams = {													
									id: node.id,															
									method: 'POST'															
								};																			
							}																				
						}																					
					}),																						
				 	root : new Ext.tree.AsyncTreeNode({id:'0',text:'根结点'})									
				 }), 																						
				 selectNodeModel:'leaf', 																	
				 listeners:{'afterchange':function(lnode,n,o){Ext.getCmp('o_id').setValue(n.id);}}
			}),{																							
					hidden : true,																				
					id : 'o_id',																
					name : 'parentId'
			},{
				fieldLabel:'角色描述',
                maxLength : 30,
                maxLengthText : '角色描述的最大长度为30个字符',	
                name:'roleName'
			}],																								
			buttons : [{																						
				text : '保存',																					
				iconCls : 'save',																				
				handler : role.save
			},{																									
				text : '重置',																					
				iconCls : 'refresh',																				
				handler :role.reset																						
			}]	
        };
	}
});

//保存数据
role.save = function(){
	var win = this.ownerCt.ownerCt.ownerCt;//当前win
	var form = this.ownerCt.ownerCt.form;																						
  	var roleId = this.ownerCt.ownerCt.findByType('hidden')[0].getValue();											
	var url = roleId==0?'role/addRole.jhtml':'role/modRole.jhtml';												
	if (form.isValid()) {																					
		form.submit({																						
			url : url,																						
			waitTitle : '提示',																				
			method : 'POST',																				
			waitMsg : '正在提交数据,请稍候.....',																	
			success : function(form, action) {																
				Ext.Msg.alert('提示',action.result.msg, function() {											
					win.hide();
					Ext.getCmp(role.parentId).items.get(0).items.get(1).store.reload();//刷新grid
				});																							
			},																								
			failure : function(form, action) {																
				Ext.Msg.alert('提示',action.result.msg, function() {											
					form.reset();
				});																							
			}																								
		});																									
	}			
};

//清空表单
role.reset = function(){
	var win_form = this.ownerCt.ownerCt;
	win_form.form.reset();
};
//组权限树
role.authWin = role.authWin || Ext.extend(Ext.Window,{
	initComponent:function(){
		Ext.apply(this, {
			resizable : false,																					
			animateTarget : document.body,																		
			closeAction: 'hide',																				
			modal: true,
			width: 600,
			height: 450,
			layout:'border',
			items:[this.getTree(),this.getCheckPanel()]
		}),
		role.authWin.superclass.initComponent.call(this);
	},
	getTree:function(){
		return {
			xtype:'treepanel',
			width: 200,
			split : true,
			region : 'west',
			root : new Ext.tree.AsyncTreeNode({
				id : '0',
				text :'根节点',
				expanded : true
			}),
			rootVisible:false,
			border:false,
			loader : new Ext.tree.TreeLoader({
				baseAttrs : {},
				dataUrl : 'module/getModuleTree.jhtml',
				listeners: {
					'beforeload':function(treeloader, node) {
						treeloader.baseParams = {
							id: node.id,
							method: 'POST'
						};
					}
				}
			}),
			autoScroll : true,
			listeners:{'click':function(node){
				var grid = this.ownerCt.items.get(1);
				role.clickModuleTree(node,grid);
			}}
	  };
	},
	getCheckPanel:function(){
		return new role.actionGrid();
	}
});

role.actionGrid = role.actionGrid || Ext.extend(Ext.grid.GridPanel,{
	 initComponent:function(){
	 	var sm = new Ext.grid.CheckboxSelectionModel();
	 	var cm = new Ext.grid.ColumnModel([
        		 sm,new Ext.grid.RowNumberer(),
		         {header:'操作ID',dataIndex:"actionId", hidden:true},
		         {header:'操作名',dataIndex:"actionName"},
		         {header:'模块名',dataIndex:"moduleText"},
		         {header:'tips',dataIndex:"tooltip"}
			         
	    ]);
	    cm.defaultSortable = true;

	    var fields = [
				 {name:"actionId"},
				 {name:"actionName"},
				 {name:"moduleText"},
				 {name:"tooltip"}
		];
		var ds = new Ext.data.Store({
				proxy:new Ext.data.HttpProxy({
		        	method: 'POST',
		        	url:'action/getDataList.jhtml'
		        }),
		        reader:new Ext.data.JsonReader({
		            root:'rows',
		            totalProperty:'results',
		            fields: fields
		        })
		        
		});
	    var tbar = [{
	    	text:'保存',tooltip: '保存',iconCls:'save',handler:this.saveFn
	    }];
	   Ext.apply(this, {
		 	store:ds,
            sm:sm,
            cm:cm,
            title:'操作列表',
            border:false,
            region : 'center',
    		stripeRows:true,
            loadMask: {msg:'正在加载数据，请稍候....'},
			layout:'fit',
            tbar:tbar
		 });
	 role.actionGrid.superclass.initComponent.call(this);
	},
	//save
	saveFn:function(){
		var node = this.ownerCt.ownerCt.ownerCt.items.get(0).getSelectionModel().getSelectedNode();//选中的节点
		var win = this.ownerCt.ownerCt.ownerCt;
		if(!node){
			Ext.Msg.alert("提示",'请选择要授权的菜单！');
			return;
		}
		var record = Ext.getCmp(role.parentId).items.get(0).items.get(1).getSelectionModel().getSelected();//选中的角色
		var r = this.ownerCt.ownerCt.ownerCt.items.get(1).getSelectionModel().getSelections();//选中的操作
		var data ='';
	    for(var i=0; i<r.length; i++){
	   		data =data+r[i].data.actionId+',';
	    }
	    if(data!=''){
			data =  data.substring(0, data.length-1);
	    }
	    Ext.Ajax.request({
	    	url:'role/saveRoleAuth.jhtml',
	    	method:'POST',
	    	params:{
	    		roleId:record.data.roleId,
	    		moduleId:node.id,
	    		actionIds:data
	    	},
	    	callback: function(resp,opts) {alert(1);
	           var respText = Ext.util.JSON.decode(resp.responseText);
	           if(respText.success){
	           	 win.hide();
	           }
	           Ext.Msg.alert('提示', respText.msg);   
	    	}    
	    });
	}
});

//点击模块树显示操作
role.clickModuleTree=function(node,grid){
	var record = Ext.getCmp(role.parentId).items.get(0).items.get(1).getSelectionModel().getSelected();//选中的角色
	if (record) {
		Ext.Ajax.request({
			url : 'role/getActionByMuduleId.jhtml',
			method : 'POST',
			params : {
				roleId : record.data.roleId,
				moduleId : node.id
			},
			success : function(resp, opts) {
				var respText = Ext.util.JSON.decode(resp.responseText);
				grid.getStore().load({
					params : {
						moduleId : node.id,
						roleId : record.data.roleId
					},
					callback : function(data) {
						if (data) {
							var rowCount = grid.getStore().getCount();
							var tmpArry = new Array();
							for (var i = 0; i < rowCount; i++) {
								for (var j = 0; j < respText.length; j++) {
									if (grid.getStore().getAt(i).get("actionId") == respText[j].actionId) {
										tmpArry.push(i);
									}
								}
							}
							grid.getSelectionModel().selectRows(tmpArry);//自动选中已有的权限
						}
					}
				});
			},
			failure : function(resp, opts) {
				var respText = Ext.util.JSON.decode(resp.responseText);
				Ext.Msg.alert('错误', respText.msg);
			}
		});
	}
};